<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="二叉树与哈夫曼编码 二叉树作为一种基础的数据结构，其独特的递归定义和多样化的类型，如满二叉树、完全二叉树等，为解决诸如查找、排序及编码等问题提供了强大的支持，而哈夫曼编码通过构建最优二叉树实现了数据的高效压缩。">
<meta property="og:type" content="article">
<meta property="og:title" content="09.二叉树与哈夫曼编码">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="二叉树与哈夫曼编码 二叉树作为一种基础的数据结构，其独特的递归定义和多样化的类型，如满二叉树、完全二叉树等，为解决诸如查找、排序及编码等问题提供了强大的支持，而哈夫曼编码通过构建最优二叉树实现了数据的高效压缩。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/tree.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_full.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_complete.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_traversing.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_restore.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/huffman_base.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/huffman_best_prefix.svg">
<meta property="article:published_time" content="2025-03-12T07:46:30.000Z">
<meta property="article:modified_time" content="2025-03-13T07:51:01.582Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/tree.svg">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/","path":"2025-03-12-09-二叉树与哈夫曼编码/","title":"09.二叉树与哈夫曼编码"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>09.二叉树与哈夫曼编码 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81"><span class="nav-number">1.</span> <span class="nav-text">二叉树与哈夫曼编码</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A0%91"><span class="nav-number">1.1.</span> <span class="nav-text">树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="nav-number">1.2.</span> <span class="nav-text">二叉树</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%81%8D%E5%8E%86%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="nav-number">1.2.1.</span> <span class="nav-text">遍历二叉树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E7%9F%A5%E9%81%93%E4%B8%AD%E5%BA%8F%E5%92%8C%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E8%BF%98%E5%8E%9F%E4%BA%8C%E5%8F%89%E6%A0%91%E7%BB%93%E6%9E%84"><span class="nav-number">1.2.2.</span> <span class="nav-text">例：知道中序和后序遍历，还原二叉树结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91"><span class="nav-number">1.2.3.</span> <span class="nav-text">二叉搜索树</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%93%88%E5%A4%AB%E6%9B%BC%E6%A0%91%E4%B8%8E%E7%BC%96%E7%A0%81"><span class="nav-number">1.3.</span> <span class="nav-text">哈夫曼树与编码</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="09.二叉树与哈夫曼编码 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          09.二叉树与哈夫曼编码
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-03-12 15:46:30" itemprop="dateCreated datePublished" datetime="2025-03-12T15:46:30+08:00">2025-03-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-03-13 15:51:01" itemprop="dateModified" datetime="2025-03-13T15:51:01+08:00">2025-03-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="二叉树与哈夫曼编码">二叉树与哈夫曼编码</h1>
<p>二叉树作为一种基础的数据结构，其独特的递归定义和多样化的类型，如满二叉树、完全二叉树等，为解决诸如查找、排序及编码等问题提供了强大的支持，而哈夫曼编码通过构建最优二叉树实现了数据的高效压缩。</p>
<span id="more"></span>
<h2 id="树">树</h2>
<p>递归式定义：一个根节点带0到多个子节点，每个子节点可以是一棵子树的根，子树也符合树的定义。</p>
<img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/tree.svg" class="" title="树的递归式定义">
<p>名词表：</p>
<ul>
<li><p>根：没有前驱</p></li>
<li><p>叶：没有后继</p></li>
<li><p>森林：多棵不相交的树</p></li>
<li><p>有序树：子树从左到右有序</p></li>
<li><p>无序树：一个根的不同子树可互换位置</p></li>
<li><p>父节点：直接前驱</p></li>
<li><p>子节点：直接后继</p></li>
<li><p>兄弟节点：同一个父节点的子节点</p></li>
<li><p>堂兄弟：两个节点的父节点不同且位于同一层</p></li>
<li><p>祖先：该节点到根节点路径上的所有节点</p></li>
<li><p>子孙：该节点子树中的任意节点</p></li>
<li><p>节点的度：一个节点的子节点数量</p></li>
<li><p>节点的层次：根节点到该节点的层数</p></li>
<li><p>终端节点：度为0的节点，即叶子</p></li>
<li><p>分支节点：度不为0的节点</p></li>
<li><p>树的度：所有节点的度的最大值</p></li>
<li><p>树的深度：最大的层数</p></li>
<li><p>满二叉树：每层都充满了，1层有1个点，2层有3个点，3层有7个点，找找规律~</p>
<ul>
<li><img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_full.svg" class="" title="满二叉树"></li>
</ul></li>
<li><p>完全二叉树：除了最后面一层外全满，最后一层的点也聚集在“左边”，确定点的个数就完全可以确定完全二叉树的形态</p>
<ul>
<li><img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_complete.svg" class="" title="完全二叉树"></li>
</ul></li>
<li><p>满二叉树与完全二叉树特性：如果从 1 开始一行一行地编号，对编号
<span class="math inline">\(i\)</span> 的节点，父节点编号 <span
class="math inline">\(i/2\)</span> ，左子节点 <span
class="math inline">\(i*2\)</span> ，右子节点 <span
class="math inline">\(i*2+1\)</span></p></li>
</ul>
<h2 id="二叉树">二叉树</h2>
<ul>
<li>所有节点度不大于2的树</li>
<li>有序树，即子树有左右之分</li>
</ul>
<p>也即二叉树是度为2的有序树的专有名词。</p>
<p>度为 2 的树，普通树与二叉树的典型区别：</p>
<ul>
<li>3个节点的二叉树有 5 种形态</li>
<li>3个节点的度为 2 的普通树有 2 种形态</li>
</ul>
<p>自行尝试画出它们</p>
<h3 id="遍历二叉树">遍历二叉树</h3>
<img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_traversing.svg" class="" title="二叉树遍历">
<p>访问顺序： 先序 <strong style="color:red;">D</strong>
<strong style="color:blue;">L</strong>
<strong style="color:green;">R</strong>、中序
<strong style="color:blue;">L</strong>
<strong style="color:red">D</strong>
<strong style="color:green;">R</strong>、后序
<strong style="color:blue">L</strong>
<strong style="color:green;">R</strong>
<strong style="color:red">D</strong></p>
<p>上图二叉树的三个访问顺序的输出结果是</p>
<ul>
<li>先序遍历：A B D E C <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Pre</span><span class="params">(<span class="type">int</span> now)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 对数据做一个预定义的任务</span></span><br><span class="line">    <span class="comment">// 就是访问了这个数据</span></span><br><span class="line">    <span class="comment">// 比如printf(&quot;%d\n&quot;, data);</span></span><br><span class="line">    <span class="built_in">DoSomething</span>(tr[now].data);</span><br><span class="line">    <span class="comment">// 访问左子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].left != fakeNull)</span><br><span class="line">    <span class="built_in">Pre</span>(tr[now].left);</span><br><span class="line">    <span class="comment">// 访问右子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].right != fakeNull)</span><br><span class="line">    <span class="built_in">Pre</span>(tr[now].right);</span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure></li>
<li>中序遍历：D B E A C <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">In</span><span class="params">(<span class="type">int</span> now)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 访问左子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].left != fakeNull)</span><br><span class="line">    <span class="built_in">In</span>(tr[now].left);</span><br><span class="line">    <span class="comment">// 访问当前节点数据</span></span><br><span class="line">    <span class="built_in">DoSomething</span>(tr[now].data);</span><br><span class="line">    <span class="comment">// 访问右子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].right != fakeNull)</span><br><span class="line">    <span class="built_in">In</span>(tr[now].right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>后序遍历：D E B C A <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Post</span><span class="params">(<span class="type">int</span> now)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 访问左子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].left != fakeNull)</span><br><span class="line">    <span class="built_in">Post</span>(tr[now].left);</span><br><span class="line">    <span class="comment">// 访问右子树</span></span><br><span class="line">    <span class="keyword">if</span>(tr[now].right != fakeNull)</span><br><span class="line">    <span class="built_in">Post</span>(tr[now].right);</span><br><span class="line">    <span class="comment">// 访问当前节点数据</span></span><br><span class="line">    <span class="built_in">DoSomething</span>(tr[now].data);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3
id="例知道中序和后序遍历还原二叉树结构">例：知道中序和后序遍历，还原二叉树结构</h3>
<p>已知一棵二叉树的中序序列和后序序列分别是BDCEAFHG 和
DECBHGFA，请画出这棵二叉树</p>
<ol type="1">
<li>由后序遍历特征，根节点必在后序序列尾部（A）由</li>
<li>中序遍历特征，根节点必在其中间，而且其左部必全部是左子树子孙（BDCE），其右部必全部是右子树子孙（FHG）</li>
<li>根据后序中的DECB子树可确定B为A的左孩子，根据HGF子串可确定F为A的右孩子；以此类推，从而可以递归完成建树。</li>
</ol>
<img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/binary_restore.svg" class="" title="二叉树三序还原">
<h3 id="二叉搜索树">二叉搜索树</h3>
<p>如果递归式定义并构建一个左子树所有节点值都比根节点值小，所有右子树节点值都比根大，就可以很快地做一些查找工作，比二分查找的优势在于，二叉树可以不断地动态添加数据，并在查找时保持二分查找的效率。</p>
<h2 id="哈夫曼树与编码">哈夫曼树与编码</h2>
<p>当有树上的一系列查找工作，经过树上路径的总次数受数据比例和树的结构影响，如何在知道结点访问比例的情况下，优化树的结构？</p>
<img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/huffman_base.svg" class="" title="编码的改进">
<p>哈夫曼树是一种根据字符出现频率构建的二叉树，出现频率高的字符编码短（靠近树根），频率低的编码长（远离树根），通过这种最短前缀编码方式实现数据的高效压缩。</p>
<p>初始化：每个结点作为独立的树（只有根结点的树）</p>
<ol type="1">
<li>取出权重最小的两棵树</li>
<li>新建一个根节点，左右子树分别为这两棵树，根节点权重为两棵树权重和</li>
<li>把新建的树放回</li>
<li>重复1~3，直到成为一棵树</li>
</ol>
<p>tip
：如何找权重最小的两棵树？规模小就暴力找，规模大可以用<strong>堆</strong>或者<code>priority_queue</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(q.<span class="built_in">size</span>() &gt; <span class="number">1</span>)</span><br><span class="line">&#123;</span><br><span class="line">    Node ln = q.<span class="built_in">top</span>(); q.<span class="built_in">pop</span>(); <span class="comment">// q是priority_queue</span></span><br><span class="line">    Node rn = q.<span class="built_in">top</span>(); q.<span class="built_in">pop</span>();</span><br><span class="line">    tr[tp].<span class="built_in">Init</span>();</span><br><span class="line">    tr[tp].data = ln.data + rn.data;</span><br><span class="line">    tr[tp].address = tp;</span><br><span class="line">    tr[tp].l = ln.address;</span><br><span class="line">    tr[tp].r = rn.address;</span><br><span class="line">    tr[ln.address].parent = tr[rn.address].parent = tp;</span><br><span class="line">    q.<span class="built_in">push</span>(tr[tp ++]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在远程通讯中，要将待传字符转换成二进制的字符串，怎样编码才能使它们组成的报文在网络中传得最快？</p>
<p>例：对<code>ABACCDA</code>编码，等长编码假设如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">A    00</span><br><span class="line">B    01</span><br><span class="line">C    10</span><br><span class="line">D    11</span><br></pre></td></tr></table></figure>
<p>编码结果是<code>000110010101100</code></p>
<p>如果不等长编码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">A    0</span><br><span class="line">B    00</span><br><span class="line">C    1</span><br><span class="line">D    01</span><br></pre></td></tr></table></figure>
<p>就可以是 <code>000011010</code></p>
<p>但是这样有问题，遇到<code>00</code>的时候，是一个<code>B</code>还是两个<code>A</code>呢？所以在设计不等长的编码时，需要让<strong>任一字符的编码都不是另一个字符的编码的前缀</strong>，这就是”前缀编码”，利用二叉树设计的哈夫曼编码就是最优前缀码。</p>
<img src="/2025-03-12-09-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%8E%E5%93%88%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/huffman_best_prefix.svg" class="" title="哈夫曼编码基本原理">
<p>编解码方式参考：</p>
<ol type="1">
<li>以字符出现频率为权值，构建赫夫曼树</li>
<li>编码：从字符对应的叶结点出发走到根结点，结点需保存parent信息
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">Encoding</span><span class="params">(<span class="type">char</span> st[], <span class="type">char</span> res[])</span></span>&#123;</span><br><span class="line">    <span class="type">int</span> resLen = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="built_in">strlen</span>(st) - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i --)&#123;</span><br><span class="line">        <span class="comment">// iLetter 为要编码的字符对应的结点编号</span></span><br><span class="line">        <span class="type">int</span> iLetter = <span class="built_in">GetCharNode</span>(st[i]);</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = iLetter; tr[j].parent != <span class="number">-1</span>; j = tr[j].parent)</span><br><span class="line">        res[resLen ++] = (j == tr[tr[j].parent].nex[<span class="number">1</span>]) + <span class="string">&#x27;0&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 从叶结点“上”去得到的编码是逆序的</span></span><br><span class="line">    <span class="comment">// 所以反向扫明文，得到结果再整体翻转一下</span></span><br><span class="line">    std::<span class="built_in">reverse</span>(res, res + resLen);</span><br><span class="line">    res[resLen] = <span class="string">&#x27;\0&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> resLen;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>解码：从根节点出发通过编码找到叶子结点 <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Decoding</span><span class="params">(<span class="type">char</span> code[], <span class="type">char</span> res[])</span></span>&#123;</span><br><span class="line">    <span class="type">int</span> resLen = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>, j = tp - <span class="number">1</span>; code[i]; i ++) &#123;</span><br><span class="line">        <span class="comment">// nex[0] 表示 left，nex[1] 表示 right</span></span><br><span class="line">        <span class="keyword">if</span>(tr[j].nex[code[i] - <span class="string">&#x27;0&#x27;</span>] == <span class="number">-1</span>) <span class="keyword">break</span>;</span><br><span class="line">        j = tr[j].nex[code[i] - <span class="string">&#x27;0&#x27;</span>];</span><br><span class="line">        <span class="keyword">if</span>(tr[j].nex[<span class="number">0</span>] == <span class="number">-1</span> &amp;&amp; tr[j].nex[<span class="number">1</span>] == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="comment">// 左右指针都空（-1），到了叶节点</span></span><br><span class="line">            res[resLen ++] = val[tr[j].ith];</span><br><span class="line">            j = tp - <span class="number">1</span>; <span class="comment">// 回到根节点解码紧贴着的下一个字符</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-03-10-08-%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97/" rel="prev" title="08.栈与队列">
                  <i class="fa fa-angle-left"></i> 08.栈与队列
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-03-12-10-%E5%93%88%E5%B8%8C%E4%B8%8E%E5%AD%97%E5%85%B8%E6%A0%91/" rel="next" title="10.哈希与字典树">
                  10.哈希与字典树 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
